package com.tgpms.web.tongfei.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tgpms.common.MultipartFileToFile;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.TongfeiController;
import com.tgpms.web.tongfei.entity.Hispspipefile;
import com.tgpms.web.tongfei.entity.InHistoryLine;
import com.tgpms.web.tongfei.pojo.Hispsnode;
import com.tgpms.web.tongfei.pojo.Hispspipe;
import com.tgpms.web.tongfei.pojo.R;
import com.tgpms.web.tongfei.service.IInHistoryLineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * <p>
 * 控制层
 * </p>
 *
 * @author jl
 * @since 2020-11-25
 */
@Api(value = "InHistoryLineController", tags = "历史遗留管网信息管线相关接口")
@RestController
@RequestMapping("tongfei")
public class InHistoryLineController {
    @Value("${tongfei.path}")
    private String host;
    private String addHispspipe = "/tofly-sxgk/hispspipe"; // 历史管线
    @Resource
    private RedisTemplate<String, Object> redis;
    @Autowired
    private IInHistoryLineService inHistoryLineService;

    /**
     * 新增历史遗留管网信息管线
     */
    @ApiOperation(value = "新增历史遗留管网信息管线", notes = "新增历史遗留管网信息管线", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/hispspipe")
    public Result addHispspipe(@RequestParam(value = "hispspipe") String jsonString, HttpServletRequest request) {
        InHistoryLine inHistoryLine = JSON.parseObject(jsonString, InHistoryLine.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(inHistoryLine.getHispspipefileList())) {
                List<Hispspipefile> hispspipefileList = inHistoryLine.getHispspipefileList();
                for (int i = 0; i < hispspipefileList.size(); i++) {
                    Hispspipefile hispspipefile = hispspipefileList.get(i);// 图片
                    paramMap.put("hispspipefileList[" + i + "].fileName", hispspipefile.getFileName());
                    paramMap.put("hispspipefileList[" + i + "].distance", hispspipefile.getDistance());
                    paramMap.put("hispspipefileList[" + i + "].latitude", hispspipefile.getLatitude());
                    paramMap.put("hispspipefileList[" + i + "].longitude", hispspipefile.getLongitude());
                    paramMap.put("hispspipefileList[" + i + "].sxCoor", hispspipefile.getSxCoor());
                    paramMap.put("hispspipefileList[" + i + "].syCoor", hispspipefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(hispspipefile.getFileName(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(inHistoryLine, false, true));
            paramMap.remove("hispspipefileList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + addHispspipe)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地新增
                String json = JSON.toJSONString(r.getResult());
                Hispsnode data = JSON.parseObject(json, Hispsnode.class);
                inHistoryLine.setRowstamp(String.valueOf(data.getId()));
                inHistoryLine.setInsertUser(this.getUsername(token));
                return inHistoryLineService.addInHistoryLine(inHistoryLine);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 修改历史遗留管网信息管线
     */
    @ApiOperation(value = "修改历史遗留管网信息管线", notes = "修改历史遗留管网信息管线", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/updateHispspipe")
    public Result updateHispspipe(@RequestParam(value = "hispspipe") String jsonString, HttpServletRequest request) {
        Hispspipe hispspipe = JSON.parseObject(jsonString, Hispspipe.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(hispspipe.getHispspipefileList())) {
                List<Hispspipefile> hispspipefileList = hispspipe.getHispspipefileList();
                for (int i = 0; i < hispspipefileList.size(); i++) {
                    Hispspipefile hispspipefile = hispspipefileList.get(i);// 图片
                    paramMap.put("hispspipefileList[" + i + "].fileName", hispspipefile.getFileName());
                    paramMap.put("hispspipefileList[" + i + "].distance", hispspipefile.getDistance());
                    paramMap.put("hispspipefileList[" + i + "].latitude", hispspipefile.getLatitude());
                    paramMap.put("hispspipefileList[" + i + "].longitude", hispspipefile.getLongitude());
                    paramMap.put("hispspipefileList[" + i + "].sxCoor", hispspipefile.getSxCoor());
                    paramMap.put("hispspipefileList[" + i + "].syCoor", hispspipefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(hispspipefile.getFileName(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(hispspipe, false, true));
            paramMap.remove("hispspipefileList");
            paramMap.remove("createTime");

//        List<Hispspipefile> hispspipefileList = hispspipe.getHispspipefileList();
//        MultipartFile[] files = new MultipartFile[hispspipefileList.size()];
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        // 获取文件map集合
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        int m = 0;
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            // 获取单个文件
//            MultipartFile mf = entity.getValue();
//            files[m] = mf;
//            m++;
//        }
//
//        // 调用同飞修改接口
//        Map<String, Object> paramMap = BeanUtil.beanToMap(hispspipe, false, true);
//        paramMap.remove("hispspipefileList");
//        File[] images = new File[hispspipefileList.size()];
//        try {
//            if (files.length > 0) {
//                for (int i = 0; i < files.length; i++) {
//                    String filename = files[i].getOriginalFilename();
//                    paramMap.put("hispspipefileList[" + i + "].fileName", filename);
//                    paramMap.put("hispspipefileList[" + i + "].distance", hispspipe.getHispspipefileList().get(i).getDistance());
//                    paramMap.put("hispspipefileList[" + i + "].latitude", hispspipe.getHispspipefileList().get(i).getLatitude());
//                    paramMap.put("hispspipefileList[" + i + "].longitude", hispspipe.getHispspipefileList().get(i).getLongitude());
//                    paramMap.put("hispspipefileList[" + i + "].sxCoor", hispspipe.getHispspipefileList().get(i).getSxCoor());
//                    paramMap.put("hispspipefileList[" + i + "].syCoor", hispspipe.getHispspipefileList().get(i).getSyCoor());
//                    File image = MultipartFileToFile.multipartFileToFile(files[i]);
//                    paramMap.put(filename, image);
//                    images[i] = image;
//                }
//            }
            String token = request.getHeader("tfToken");
            String body = HttpRequest.put(host + addHispspipe)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地修改
                String json = JSON.toJSONString(r.getResult());
                Hispspipe data = JSON.parseObject(json, Hispspipe.class);
                InHistoryLine inHistoryLine = inHistoryLineService.getHispspipeByRowstamp(String.valueOf(data.getId()));
                BeanUtil.copyProperties(data, inHistoryLine, "id");
                inHistoryLine.setModifyUser(this.getUsername(token));
                inHistoryLine.setModifyDate(new Date());
                return inHistoryLineService.updateInHistoryLine(inHistoryLine);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 分页查询历史遗留管网信息管线
     */
    @ApiOperation(value = "分页查询历史遗留管网信息管线", notes = "分页查询历史遗留管网信息管线", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/hispspipe/page")
    public Result page(Hispspipe hispspipe, HttpServletRequest request) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(hispspipe, false, true);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/hispspipe/page", paramMap, request);
    }

    private String getUsername(String token) {
        return (String) redis.opsForValue().get(token);
    }
}
